import sys
import glob
import pickle
from pathlib import Path

import pandas as pd

BASE = Path(__file__).resolve().parents[1]
# Prefer the latest pred_best_*.pkl
candidates = sorted(BASE.glob('pred_best_*.pkl'), key=lambda p: p.stat().st_mtime, reverse=True)
if not candidates:
    print('No pred_best_*.pkl found under', BASE)
    sys.exit(1)
pred_path = candidates[0]
print('Using prediction file:', pred_path)

with open(pred_path, 'rb') as f:
    pred = pickle.load(f)

# Ensure DataFrame with proper index
if isinstance(pred, pd.Series):
    pred = pred.to_frame('score')

# Select daily top-50 by score
pred = pred.sort_values('score', ascending=False)
# groupby datetime level 0
top = (
    pred.groupby(level=0)
        .head(50)
        .reset_index()
        .rename(columns={'datetime': 'date'})
)
out_csv = BASE / 'top50_best_run.csv'
print('Saving:', out_csv)

top.to_csv(out_csv, index=False)
print('Done. Rows:', len(top))